<!DOCTYPE html>
<html class="loading" lang="en" data-textdirection="ltr">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
    <meta name="author" content="PIXINVENT">
    <title>999后台管理系统</title>
    <script src="./date/js/Dream.js"></script>
    <script src="./app-assets/js/Http.js"></script>
    <link rel="stylesheet" type="text/css" href="app-assets/css/vendors.css">
    <link rel="stylesheet" type="text/css" href="app-assets/css/vertical-menu.css">
    <link rel="stylesheet" type="text/css" href="app-assets/css/bootstrap-extended.css">
    <link href="./date/css/layui.css" rel="stylesheet">
    <style>
    .layui-menu {
        position: fixed;
        top: 16px;
        left: 16px;
        width: 260px;
        z-index: 1000;
        max-height: calc(100vh - 32px); /* 防止内容溢出 */
        overflow-y: auto; /* 添加垂直滚动条 */
      }
    .center-content {
        display: flex;
        justify-content: center;
        align-items: center;
        /* height: 100vh; 使容器高度占满整个视口 */
    }
    .search-container {
        display: flex;
        align-items: center;
    }
    .search-container h3 {
        margin-right: 15px;
    }
    .layui-col-md6{
        width: 450px;
    }
    #shoppingNumber {
        /*设置成盒子模型*/
        display: inline-block;
        background-color: #333333;
        border-radius: 50%;
        /* 设置宽高 */
        width: 18px;
        height: 18px;
        /* 设置文字居中 */
        text-align: center;
        /* 设置文字居中 */
        line-height: 18px;
        /* 设置文字大小 */
        font-size: 8px;
        color: white;
    }
    </style>
</head>
<body>
<div class="content-wrapper">
  <div class="content-header center-content">
    <div class="search-container">
        <h3 class="content-header-title mb-0">采购商品</h3>
        <div class="input-group" style="width: 300px;"> 
            <input type="text" class="form-control" placeholder="搜索商品">
            <div class="input-group-append">
                <button class="btn btn-primary" type="button" id="productNameSearch">搜索</button>
            </div><br>
            <div class="layui-menu-body-title">
              <a href="javascript:;" class="supplier-link" id="showAll">展示全部</a>
            </div>
        </div>
    </div>
    <div class="cart-container">
      <a id="showSMessage"><span>购物车 (<span id="cartCount">0</span>)</span></a>
    </div>
  </div>
</div>  
<div class="content-wrapper">
    <div class="row">
          <div class="layui-panel" style="width: 260px; margin: 16px;">
            <ul class="layui-menu" id="demo-menu">
              
            </ul>
          </div>
          
          <div class="layui-bg-gray" style="padding: 16px;">
            <div class="layui-row layui-col-space15" id="showShangpMessage">
              
            </div>
          </div>
          <script src="./date/js/layui.js"></script>
          



          

 <!--购物车-->
 <div class="cart-box">
  <div class="cart-title">
      <div class="pull-left">
          <span style="  font-size: 18px;" onclick="showS()"><a href="#">订购车</a></span>&nbsp;<span
              id="shoppingNumber">0</span>
      </div>
      <div class="pull-right">
          合计：<span class="total-price red" id="totalAmount">0</span>&nbsp;&nbsp;&nbsp;
          <a href="#" class="btn btn-primary" onclick="getTO()">生成采购订单</a>
          <a href="#" class="btn btn-danger" onclick="getClear()">清空</a>
      </div>
  </div>
  <div class="cart-list">
      <table id="cartTab" class="table">
          <thead>
          <tr>
              <th>商品名称</th>
              <th>商品价格</th>
              <th>商品数量</th>
              <th>操作</th>
              <th>小计</th>
          </tr>
          </thead>
          <tbody id="cartT">
          </tbody>
      </table>
  </div>
</div>

</div>

<script src="app-assets/js/vendors.min.js" type="text/javascript"></script>
<script src="app-assets/js/app-menu.js" type="text/javascript"></script>
<script src="app-assets/js/app.js" type="text/javascript"></script>
<script src="app-assets/js/echarts.min.js" type="text/javascript"></script>

</body>
</html>
<script>
// 清空
function getClear(){
  cartItems = [];
  showGouWuChe();
}



var cartItems = [];

// 加入购物车事件处理
 function addCart(product) {
  // 弹窗显示当前点击的商品ID


  // 检查商品是否已经存在于购物车
  let existingProduct= cartItems.find(item => item.productId === product.productId);
  if(existingProduct){
    existingProduct.quantity += 1;

  } else {
    // 如果商品不存在于购物车，创建一个新的购物车条目
    product.quantity = 1;
    cartItems.push({...product,quantity:1});
  }
  updateCartCount();
  showGouWuChe()
  }
// 更新购物车计数
function updateCartCount() {
  $('#cartCount').text(Object.keys(cartItems).length);
  $('#shoppingNumber').text(Object.keys(cartItems).length);
}

// 鼠标滑轮监控
let pageNum = 1;
var pages = 0;

$(function() {
  console.log(window.sessionStorage.getItem("empName"))
            var loginMessage = window.sessionStorage.getItem("empName")
            if(loginMessage==null){
                alert("请先登录")
                window.location.href="./index.html"
            }
  selectAll("", "", 1);
});
// 页面加载
function selectAll(productName, supplierName, pageNum) {
  $.ajax({
      'url': HTTP.getUserInfo + '/products',
      'type': 'get',
      'dataType': 'json',
      'data': { productName, supplierName, pageNum },
      'success': function(data) {
        console.log(data);
        pages = data.data.pages;
        // $('#showShangpMessage').empty();
        var dataMessage = data.data.list;
        
        dataMessage.forEach(function(item) {
          var str = `
            <div class="layui-col-md6" data-product-id="${item.id}" value="${item.id}">
              <div class="layui-card">
                <div class="layui-card-body">
                  <img src="${HTTP.getUserInfo + item.imageUrl}" style="width: 300px;height: 200px;"><br>
                  商品名称:<span>${item.productName}</span>&nbsp;&nbsp;&nbsp;商品采购价:<span>${item.purchasePrice}</span><br>建议商品售价:${item.price}<br>
                  <button class="layui-btn layui-btn-normal" onclick='addCart(`+JSON.stringify(item)+`)'>加入购物车</button>
                </div>
              </div>
            </div>
          `;
          $('#showShangpMessage').append(str);
        });
        selectAllSuppliers();
      }
  });
}
// 查询所有的供应商
function selectAllSuppliers() {
  $.ajax({
    'url': 'http://localhost:18081/suppliers/list',
    'type': 'get',
    'dataType': 'json',
    success: function (data) {
      $('#demo-menu').empty();
      var dataMessage = data.data;
      dataMessage.forEach(function (item) {
        var str = `
          <li lay-options="{id: 100}">
            <div class="layui-menu-body-title">
              <a href="javascript:;" class="supplier-link" data-supplier-name="${item.supplierName}">${item.supplierName}</a>
            </div>
          </li>
        `;
        $('#demo-menu').append(str);
      });
    }
  });
}

var supplierNameAll = "";
var productNameAll = "";
// 供应商列表 
layui.use(['dropdown', 'layer', 'util'], function () {
  var dropdown = layui.dropdown;
  var layer = layui.layer;
  var util = layui.util;

  // 菜单点击事件
  $(document).on('click', '.supplier-link', function () {
    pageNum = 1;
    $('#showShangpMessage').empty();
    var supplierName = $(this).data('supplier-name');
    layer.msg(supplierName);
    supplierNameAll = supplierName;
    selectAll(productNameAll, supplierNameAll, pageNum);
  });

  // 初始化加载供应商列表
  selectAllSuppliers();
});
// 商品查询
$('#productNameSearch').on('click', function() {
  pageNum = 1;
  $('#showShangpMessage').empty();
  var productName = $('.search-container input').val();
  productNameAll = productName;
  selectAll(productNameAll, supplierNameAll, pageNum);
});
// 鼠标滚轮
$(document).on("mousewheel DOMMouseScroll", function (event) {
  var delta = (event.originalEvent.wheelDelta && (event.originalEvent.wheelDelta > 0 ? 1 : -1)) ||  // chrome & ie
              (event.originalEvent.detail && (event.originalEvent.detail > 0 ? -1 : 1));              // firefox

  if (delta < 0) {
    pageNum += 1;
    if (pageNum <= pages) {
      console.log("获取后台第" + pageNum + "页数据");
      selectAll(productNameAll, supplierNameAll, pageNum);
    } else {
      console.log("已是最后一页");
    }
  }
});
// 点击展示全部
$('#showAll').on('click', function() {
  pageNum = 1;
  $('#showShangpMessage').empty();
  selectAll("", "", pageNum);
});

$('#showSMessage').on('click', function() {
  console.log(cartItems)
  showGouWuChe();
})
var totalPrice = 0;
// 展示购物车方法
function showGouWuChe(){
  totalPrice = 0;
  $('#cartT').empty();
  cartItems.forEach(function(item){
    $('#cartT').append(
      `<tr>
        <td>`+item.productName+`</td>
        <td>`+item.purchasePrice+`</td>
        <td><button onclick="addProductNum(`+item.productId+`)"  class="btn btn-primary" >+</button>`+item.quantity+`<button onclick="jianProductNum(`+item.productId+`)"  class="btn btn-primary" >-</button></td> 
        <td><a href="#" onclick="getDelete(`+item.productId+`)">删除</a></td>
        <td>`+item.purchasePrice*item.quantity+`</td>
      </tr>`  
    )
    totalPrice = totalPrice + item.purchasePrice*item.quantity;
  })
  $('#totalAmount').html(totalPrice)
}

function getDelete(productId){
  cartItems.forEach(function(itemTwo){
    if(productId==itemTwo.productId){
      cartItems.splice(itemTwo,1);
      showGouWuChe();
      return;
    }
  })
}

// 增加商品数量
function addProductNum(productId){
  cartItems.forEach(function(itemTwo){
    if(productId==itemTwo.productId){
      itemTwo.quantity+=1;
      console.log(cartItems)
      showGouWuChe();
      return;
    }
  })
}


// 减少商品数量
function jianProductNum(productId){
  cartItems.forEach(function(itemTwo){
    if(productId==itemTwo.productId){
      if(itemTwo.quantity>1){
        itemTwo.quantity-=1;
        showGouWuChe();
        return
      }else{
        alert('数量已经最低了，如果不买请删除此商品的购物车')
      }
      return;
    }
  })
}
var jieSuanShuJu = [];
// 结算按钮
function getTO(){
  // 遍历对象，给新的对象传值
  cartItems.forEach(function(item){
    var productId = item.productId;
    var quantity = item.quantity;
    var insertOrdersSuccess = {productId,quantity}
    jieSuanShuJu.push(insertOrdersSuccess)
  })
  console.log(jieSuanShuJu)


  // 转为json对象
  var JSONJieSuan = JSON.stringify(jieSuanShuJu);
  $.ajax({
    url:'http://localhost:18081/purchaseOrders/insertOrders',
    type:'post',
    data:JSONJieSuan,
    dataType:'JSON',
    contentType:'application/json',
    success:function(data){
      window.localStorage.setItem("gouwuche",cartItems)
      window.location.href='订单列表.html'
    }
  })
}

</script>